package cn.ygh.bbo.system.service.impl;

import cn.ygh.bbo.system.bean.AdminRole;
import cn.ygh.bbo.system.bean.RolePermission;
import cn.ygh.bbo.system.service.AdminRoleService;
import cn.ygh.bbo.system.service.DataFilterService;
import cn.ygh.bbo.system.service.RolePermissionService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import cn.ygh.bbo.framerwork.core.Grid;
import cn.ygh.bbo.common.exception.TipException;
import cn.ygh.bbo.common.annotation.DataScope;
import cn.ygh.bbo.system.bean.Role;
import cn.ygh.bbo.system.mapper.RoleMapper;
import cn.ygh.bbo.system.service.RoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 描述：角色  ServiceImpl
 * @author ygh
 */
@Service
public class RoleServiceImpl implements RoleService{

    private final Logger logger=LoggerFactory.getLogger(getClass());

    @Autowired
    RoleMapper mapper;

    @Autowired
    AdminRoleService adminRoleService;

    @Autowired
    RolePermissionService rolePermissionService;

    @Autowired
    DataFilterService dataFilterService;

    /**
    * 保存对象
    * @param  role 对象信息
    * @return
    */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int save(Role role) {
        //保存之前通用处理
        beforeCreate(role);
        role.def();
        return mapper.insert(role);
    }

    /**
    * 更新对象
    * @param  role 对象信息
    * @return
    */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int update(Role role) {
        if(role.getId()==null){
            throw new TipException("id can not null");
        }
        //更新之前通用处理
        beforeUpdate(role);
        role.def();
        return mapper.updateById(role);
    }

    /**
    * 批量更新
    * @param  role 对象信息
    * @param ids
    * @return
    */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateBatchByIds(Role role, Serializable[] ids) {
        if(ids==null || ids.length==0){
            throw new TipException("ids can not null");
        }
        return mapper.updateBatchByIds(role,ids);
    }

    /**
    * 根据ID删除对象
    * @param id
    * @return
    */
    @Override
    public int deleteById(Serializable id) {
        if(id==null){
            throw new TipException("id can not null");
        }
        if(checkLink(id)){
            return mapper.deleteById(id);
        }
        return 0;
    }

    /**
    * 删除关联判断
    * @param id
    */
    private boolean checkLink(Serializable id) {
        Integer i=Integer.valueOf(id.toString());
        long count=adminRoleService.getCountByAdminIdAndRoleId(null, i);
        if (count>0){
            throw new TipException(String.format("管理员相关还存在%s条数据,无法删除",count));
        }
        count=rolePermissionService.getCountByRoleIdAndPermissionId(i, null);
        if (count>0){
            throw new TipException(String.format("权限相关还存在%s条数据,无法删除",count));
        }
        count=dataFilterService.getCountByRoleId(i);
        if (count>0){
            throw new TipException(String.format("数据权限相关还存在%s条数据,无法删除",count));
        }
        return true;
    }

    /**
    * 根据ID数组批量删除对象
    * @param ids
    * @return
    */
    @Override
    public int deleteByIds(Serializable[] ids) {
        if(ids==null || ids.length==0){
            throw new TipException("ids can not null");
        }
        int result=0;
        for (Serializable id:ids){
            result+=deleteById(id);
        }
        return result;
    }

    /**
    * 根据ID获取对象
    * @param id
    * @return
    */
    @Override
    public Role getById(Serializable id) {
        if(id==null){
            throw new TipException("id can not null");
        }
        return mapper.selectById(id);
    }

    /**
    * 根据ID数组获取对象列表
    * @param ids
    * @return
    */
    @Override
    public List<Role> listfindByIn(Serializable[] ids) {
        if(ids==null || ids.length==0){
            throw new TipException("ids can not null");
        }
        return mapper.selectBatchIds(Arrays.asList(ids));
    }

    /**
    * 根据对象信息获取满足条件的对象列表
    * @param  role 对象信息
    * @param pageable 分页条件为空则不分页
    * @return
    */
    @DataScope
    @Override
    public List<Role> listfind(Role role, Pageable pageable) {
        if (pageable!=null && pageable.getPageNumber()!=0){
            PageHelper.startPage(pageable.getPageNumber()
                    , pageable.getPageSize(), false);
        }
        return mapper.selectByObj(role);
    }

    /**
    * 根据对象信息获取满足条件的对象列表和总数
    * @param  role 对象信息
    * @param pageable 分页条件
    * @return
    */
    @DataScope
    @Override
    public Grid listGrid(Role role, Pageable pageable) {
        PageHelper.startPage(pageable.getPageNumber()
                , pageable.getPageSize(), true);
        List<Role> roles = mapper.selectByObj(role);
        PageInfo<Role>pageInfo=new PageInfo<>(roles);
        Grid grid=new Grid();
        grid.setTotal((int) pageInfo.getTotal());
        grid.setRows(pageInfo.getList());
        return grid;
    }

    /**
     * 获取用户的所有角色
     *
     * @param adminId
     * @return
     */
    @Override
    public List<Role> listfindByAdminId(Integer adminId) {
        List<AdminRole>adminRoles=adminRoleService.listfindByAdminId(adminId);
        if (adminRoles.size()==0){
            return new ArrayList<>();
        }
        List<Integer>roleIds=adminRoles.stream().map(e->e.getRoleId()).collect(Collectors.toList());
        return listfindByIn(roleIds.toArray(new Integer[0]));
    }

    /**
     * 通过name获取角色
     *
     * @param name
     * @return
     */
    @Override
    public Role getByName(String name) {
        Role params=new Role();
        params.setName(name);
        List<Role>roles=listfind(params, PageRequest.of(1, 1));
        if (roles.size()>0){
            return roles.get(0);
        }
        return null;
    }

    /**
     * 权限分配
     *
     * @param roleId
     * @param permissionIds
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void createPermission(Integer roleId, String permissionIds) {
        //删除之前的权限
        rolePermissionService.deleteByRoleId(roleId);
        //添加新的权限
        if (StringUtils.isNotBlank(permissionIds)){
            String []ids=permissionIds.split(",");
            for (String id:ids){
                RolePermission rolePermission = new RolePermission(
                        roleId //角色序号
                        ,Integer.parseInt(id) //权限序号
                );
                rolePermissionService.save(rolePermission);
            }
        }
    }
}
